
const jwt = require('jsonwebtoken');
const { SECRET_KEY, WHITELIST } = require("../config/index")
//中间件
const sends = (req, res, next) => {
  res.sends = (v, msg) => res.send({ code: 200, data: v, msg: msg })
  res.sendError = (v, msg) => res.send({ code: 400, data: v, msg: msg })
  next()
}

/**
 * 校验token
*/
const checkToken = (req, res, next) => {
  if (!WHITELIST.includes(req.url)) {
    const token = req.headers.authorization

    jwt.verify(token, SECRET_KEY, (err, decoded) => {
      if (err) {
        res.send({ code: 403, data: null, msg: '登录无效或过期,请重新登陆!' })
      } else {
        if (decoded.data?.id) {
          req.userId = decoded.data?.id
          next()
        } else {
          res.send({ code: 403, data: null, msg: '登录无效或过期,请重新登陆!' })
        }
      }
    })
  } else {
    next()
  }
}
const errorHandling = (req, res) => {
  res.status(404).send({ code: 404, data: null, msg: null })
}
module.exports = { sends, checkToken, errorHandling }
